<template>
<div>
  <el-table
    :data="tableData"
    style="width: 100%"
    max-height="500px">
    <el-table-column
      fixed
      prop="fileName"
      label="文件名">
    </el-table-column>
    <el-table-column
      fixed="right"
      label="操作"
      width="120">
      <template slot-scope="scope">
		<el-button
          size="mini"
          type="primary"
          @click="downLoad(scope.$index, scope.row)">下载</el-button>
      </template>
    </el-table-column>
  </el-table>
	<el-upload
		style="margin:30px 0px"
		class="upload-demo"
		name = "files"
		action="http://localhost:8989/files/upload"
		:on-success="uploadSuccess"
		:on-error="uploadError"
		:before-upload="beforeAvatarUpload"
		multiple
		:limit="10"
  	:on-exceed="handleExceed"
		list-type="picture">
		<el-button size="small" type="success">点击上传</el-button>
		<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过30MB</div>
	</el-upload>
</div>
</template>

<script>
export default {
    name:'File',
    data() {
      return {
				search: '',
				fileList: [],
        tableData: [{
					fileName:'2020-01-10 1.jpg'
				}]
      }
    },
    methods: {
			uploadSuccess(response, file, fileList) {
				this.$message.success('上传成功！');
			},
			uploadError(err, file, fileList) {
				this.$message.error('上传失败！');
			},
			beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 30;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
					return isJPG && isLt2M;
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 30MB!');
					return isJPG && isLt2M;
				}        
			},
			handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			findAllFiles(currentPage, pageSize) {
				currentPage = currentPage ? currentPage : 1;
				pageSize = pageSize ? pageSize : this.pageSize;
				this.$http.get("http://localhost:8989/files/list").then(res => { this.tableData = res.data; })
			},
			downLoad(index, row) {
				let url = 'http://localhost:8989/files/download?fileName=' + row.fileName;
				this.axios({
				method:'get',
				url:url,
				responseType:'blob',
				}).then((data) => {
					if (!data) return;
					let url = window.URL.createObjectURL(data.data)
					let link = document.createElement('a')
					link.style.display = 'none'
					link.href = url
					link.setAttribute('download', row.fileName)
					document.body.appendChild(link)
					link.click()
				})
			},
		},
		created () {
        this.findAllFiles();
    }
}
</script>